import React, { useEffect, useMemo, useState } from "react";
import { Button, Checkbox, Image, Popup, Toast } from "antd-mobile";
import { staticImg } from "@/config";
import "./index.scss";
// import { t } from "@/utils";
import { t } from "@/lang";
import Address from "@/components/Address";
import { CloseOutline } from "antd-mobile-icons";
import DiagBtn from "@/components/DiagBtn";
import mittBus from "@/utils/mittBus";
import { createOrder, getAddress, getorderInfo } from "@/api/modules/vip_pay";
import qs from "qs";
import { getChannel } from "@/utils";
const query: Record<string, any> = qs.parse(location.search.slice(1));
console.log(query.token);
const Child: React.FC<{
  is_new_user?: boolean;
  new_sale: MemberListData;
  is_send_hardware: Boolean;
}> = ({
  is_new_user,
  new_sale,
  is_send_hardware
}) => {
    const [visible, setVisible] = useState(false);
    const [goodsItem, setGoodsItem] = useState<MemberListData>();
    const [isTrial, setIsTrial] = useState(false);
    const [orderInfo, setOrderInfo] = useState<OrderParams>();
    mittBus.on("goodsItem", (payload: MemberListData) => {
      setGoodsItem(payload);
    });
    const saleInfo = useMemo(() => {
      const res = isTrial ? new_sale : goodsItem;
      console.log(isTrial, res);
      return res;
    }, [isTrial, goodsItem]);
    const needAddresss = Boolean(saleInfo?.gift_status) || is_send_hardware;
    const onChangeExpress = (addressInfo: FreightAddress) => {
      const params = {
        shipping: saleInfo?.gift_status == 2 || is_send_hardware ? addressInfo.price : "",
        shipping_id: saleInfo?.gift_status == 2 || is_send_hardware ? addressInfo.shipping_id : undefined,
        mailing_id: needAddresss ? addressInfo.mailing_id : undefined,
        order_goods: [{
          number: 1,
          sku: saleInfo!.goods_sku
        }]
      };
      getorderInfo(params).then(res => {
        setOrderInfo({
          ...addressInfo,
          ...res.data
        });
        console.log(res);
      });
    };
    useEffect(() => {
      if (visible && !saleInfo?.gift_status) {
        getorderInfo({
          order_goods: [{
            number: 1,
            sku: saleInfo!.goods_sku
          }]
        }).then(res => {
          setOrderInfo(res.data);
        });
      }
    }, [visible]);
    const pay = async () => {
      console.log(orderInfo);
      const {
        shipping_id,
        mailing_id,
        mailing_information,
        pay_price,
        original_price
      } = orderInfo!;
      if (needAddresss && !mailing_id) {
        Toast.show("请先选择收货地址");
        return
      }
      mailing_information && (mailing_information[0].is_security = true);
      const {
        good_type,
        sku,
        number,
        soft_package_id,
        soft_name,
        vin,
        car_year,
        car_model,
        car_make
      } = orderInfo!.goods_list[0];
      const params = {
        channel_type: 1,
        channel: query.appid == "9054" ? 3 : getChannel(query.channel),
        // pay_type: 3,//暂定
        shipping_id: saleInfo?.gift_status == 2 || is_send_hardware ? shipping_id : undefined,
        device_sn: query.sn || query.serialNo,
        mailing_id: needAddresss ? mailing_id : undefined,
        mailing_information,
        good_type,
        pay_price,
        original_price: original_price!,
        order_goods: [{
          sku,
          number: number,
          soft_package_id,
          soft_name,
          vin,
          car_year,
          car_model,
          car_make
        }]
      };
      if (isTrial) {
        params.pay_price = "0";
      }
      const { code, data } = await createOrder(params)
      if (code === 0) {
        query.token = sessionStorage.getItem("token");
        query.token = query.token?.startsWith("Bearer") ? query.token!.slice(6)?.trim() : query.token;
        const payUrl = location.href.includes("h5.mythinkcar.com") ? "https://h5.mythinkcar.com/payPage/pay/cloudpay" : "https://h5.test.mythinkcar.com/payPage/pay/cloudpay";
        location.href = `${payUrl}/?${qs.stringify(query)}&orderNo=${data.order_no}`;
      } else if (code === 20001) {
        Toast.show(t('vipPay.t_30'));
      } else if (code === 20002) {
        Toast.show(t('vipPay.t_31'));
      } else if (code === 20003) {
        Toast.show(t('vipPay.t_32'));
      } else {
        Toast.show(t('vipPay.t_33'));
      }
    };
    return <div className="pay">
      <div className="trial_vip">
        {new_sale && Object.keys(new_sale).length ? <div className="flex-between">
          <Checkbox onChange={val => setIsTrial(val)}>
            {t('vipPay.t_34')}
          </Checkbox>
          $0.00
        </div> : <div>VIP ${goodsItem?.pay_price}</div>}
      </div>
      <DiagBtn onClick={() => setVisible(true)}>
        {t('vipPay.t_35')} ${saleInfo?.pay_price || 0}
      </DiagBtn>
      <Popup bodyClassName="pay_popup" visible={visible}>
        <header className="flex-between">
          <p></p>
          <p>{t('vipPay.t_36')}</p>
          <CloseOutline fontSize={16} className="close_icon" onClick={() => setVisible(false)} />
        </header>
        <main>
          {/* {<Address onChangeExpress={onChangeExpress} />} */}
          {needAddresss && <Address addrVisible={visible} onChangeExpress={onChangeExpress} />}
          <ul>
            <li>
              <span>{t('vipPay.t_37')}</span>
              <span>${orderInfo?.goods_price}</span>
            </li>
            <li>
              <span>{t('vipPay.t_38')}</span>
              <span>${orderInfo?.shipping || 0}</span>
            </li>
            <li>
              <span>{t('vipPay.t_39', {
                aa: orderInfo?.integral || 0
              })}
              </span>
              <span>-$ {orderInfo?.integral_pay_price}</span>
            </li>
            <li>
              <span>{t('vipPay.t_40')}</span>
              <span style={{
                color: "#9b0008"
              }}>${orderInfo?.pay_price}</span>
            </li>
          </ul>
        </main>
        <footer>
          <DiagBtn onClick={pay}>{t('vipPay.t_41')}</DiagBtn>
        </footer>
      </Popup>
    </div>;
  };
export default Child;